package com.boyou.sytzc.ui

import android.app.Activity
import androidx.lifecycle.MutableLiveData
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import com.boyou.sytzc.R
import com.boyou.sytzc.api.vmodel.HttpApiViewModel
import com.boyou.sytzc.ui.adapter.ServerLocalListAdapter
import com.boyou.sytzc.data.event.DeviceNoChangedEvent
import com.boyou.sytzc.databinding.ActivityInitSettingsBinding
import com.boyou.sytzc.core.appctx.AppApplication
import com.boyou.sytzc.core.appctx.AppData
import com.boyou.sytzc.utils.app.AppConfig
import com.hi.dhl.binding.viewbind
import com.yuge.yugecse.util.device.ToastUtil
import org.simple.eventbus.EventBus

class InitSettingsActivity : AppCompatActivity(), View.OnClickListener {

    private val binding by viewbind<ActivityInitSettingsBinding>()

    private val networkViewModel by viewModels<HttpApiViewModel>()

    private val appConfig by lazy { AppConfig.singleton() }

    private var handleTimeSpan: Int? = null //手动拍照时间

    private var autoTimeSpan: Int? = null //自动拍照时间

    private var realDeviceNo = MutableLiveData<String>() //设备号

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_init_settings)
        setFinishOnTouchOutside(false) //设置透明区域不可点击
        val deviceNo = intent?.getStringExtra("deviceNo") //设备号
        handleTimeSpan = appConfig.handleTimeSpan
        autoTimeSpan = appConfig.autoTimeSpan
        binding.etHandleTimeSpan.setText(handleTimeSpan.toString())
        binding.etAutoTimeSpan.setText(autoTimeSpan.toString())
        binding.etDeviceNo.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                this@InitSettingsActivity.realDeviceNo.value = s?.toString()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
        when (!deviceNo.isNullOrEmpty()) {
            true -> {
                binding.etDeviceNo.setText(deviceNo)
                getServerLocals(this@InitSettingsActivity.realDeviceNo.value) //获取服务器地址
            }
            else -> {
                binding.pbLoading.visibility = View.GONE
                ToastUtil.showGenericToast(this, "请先输入设备号")
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnDismiss -> {
                setResult(Activity.RESULT_CANCELED)
                finish()
            }
            R.id.btnRefresh -> readLoadData()
            R.id.btnSubmit -> submitAllData()
        }
    }

    private fun readLoadData() {
        if (!isDeviceNoEnabled()) {
            ToastUtil.showGenericToast(this, "请输入正确的设备号")
            return
        }
        getServerLocals(realDeviceNo.value) //获取服务器地址
    }

    private fun submitAllData() {
        if (!isDeviceNoEnabled()) {
            ToastUtil.showGenericToast(this, "请输入正确的设备号")
            return
        }
        if (binding.lvServerLocal.adapter == null || (binding.lvServerLocal.adapter?.count
                ?: 0) == 0
        ) {
            ToastUtil.showGenericToast(this, "请刷新获取服务器列表")
            return
        }
        val adapter = binding.lvServerLocal.adapter as ServerLocalListAdapter
        if (adapter.checkedItem == null) {
            ToastUtil.showGenericToast(this, "请选择服务器地址")
            return
        }
        val serverLocalInfo = adapter.checkedItem
        val domainUrl = serverLocalInfo?.url ?: AppData.DEFAULT_SERVER_URL
        val handleTimeSpan = (serverLocalInfo?.wjpz
            ?: AppData.DefaultHandleTakeCameraTime).toInt()
        val autoTimeSpan = (serverLocalInfo?.wjjs
            ?: AppData.DefaultAutoTakeCameraTime).toInt()
        appConfig.handleTimeSpan = handleTimeSpan
        appConfig.autoTimeSpan = autoTimeSpan
        appConfig.serverUrl = domainUrl
        appConfig.appFirstRun = false
        AppApplication.deviceNoManager.deviceNo = realDeviceNo.value
        EventBus.getDefault().post(DeviceNoChangedEvent(realDeviceNo.value))
        ToastUtil.showGenericToast(this, "数据配置成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    /** 设备号是否可用 **/
    private fun isDeviceNoEnabled() =
        realDeviceNo.value?.trim()?.trim('-', ' ')?.isNotEmpty() == true

    /** 获取服务器地址列表 **/
    private fun getServerLocals(deviceNo: String?) {
        binding.pbLoading.visibility = View.VISIBLE
        networkViewModel.getServerLocals(2, deviceNo) { isSuccessful, message, result ->
            binding.pbLoading.visibility = View.GONE
            if (isSuccessful && result != null && result.isNotEmpty()) {
                binding.lvServerLocal.adapter = ServerLocalListAdapter(this, result.toMutableList())
            }
            if (!TextUtils.isEmpty(message))
                ToastUtil.showGenericToast(this, message)
        }
    }

}
